package com.example.rpcdemo.server.config;

import com.example.rpcdemo.core.server.RpcServer;
import com.example.rpcdemo.api.HelloService;
import com.example.rpcdemo.service.impl.HelloServiceImpl;
import com.example.rpcdemo.registry.ServiceRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.PreDestroy;

@Configuration
public class RpcServerConfig {
    
    @Value("${rpc.server.port:8080}")
    private int port;
    
    @Value("${server.host:localhost}")
    private String host;
    
    private RpcServer rpcServer;
    
    @Bean
    public HelloService helloService() {
        return new HelloServiceImpl();
    }
    
    @Bean
    public RpcServer rpcServer(HelloService helloService) {
        rpcServer = new RpcServer(port);
        rpcServer.addService("helloService", "com.example.rpcdemo.api.HelloService", helloService);
        
        // 注册到本地注册中心
        ServiceRegistry.getInstance().register("helloService", "com.example.rpcdemo.api.HelloService", host, port);
        
        return rpcServer;
    }
    
    @PreDestroy
    public void destroy() {
        if (rpcServer != null) {
            rpcServer.stop();
        }
    }
}